/**
 * @(#)MyProtoClientHandler.java, 2018/12/26
 * <p/>
 * Copyright 2018 Netease, Inc. All rights reserved.
 * NETEASE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.chengzhi.netty.protobuf;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Random;

/**
 * @author 阮承志(wb.ruanchengzhi @ mesg.corp.netease.com)
 **/
public class MyProtoClientHandler extends SimpleChannelInboundHandler<MyMessageDTO.MyMessage> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i < 10; i++) {
            Random random = new Random();
            int flag = random.nextInt(2);
            MyMessageDTO.MyMessage build = null;
            switch (flag) {
                case 0:
                    build = MyMessageDTO.MyMessage.newBuilder()
                            .setDataType(MyMessageDTO.MyMessage.dataType.PersonType)
                            .setPerson(MyMessageDTO.Person.newBuilder()
                                    .setName("xxx").setAddress("address").build())
                            .build();

                    break;
                case 1:
                    build = MyMessageDTO.MyMessage.newBuilder()
                            .setDataType(MyMessageDTO.MyMessage.dataType.StudentType)
                            .setStudent(MyMessageDTO.Student.newBuilder()
                                    .setName("student").setAge(22).build())
                            .build();
                    break;
            }
            ctx.writeAndFlush(build);
        }
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MyMessageDTO.MyMessage msg) throws Exception {
        System.out.println("receive server response" + msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
